﻿using System;
using System.IO;
using System.Linq;
using System.Text;


namespace IDEAMS.model
{
    public class StreamWriterWrapper
    {
        private StreamWriter sw;
        private string filePath;
        private int fileSeq = 0;
        private DateTime firstWriteTm;
        private CreateFileMode fileMode = null;

        public StreamWriterWrapper(string path)
        {
            filePath = path;
            sw = new StreamWriter(filePath, false, Encoding.Default);
            sw.AutoFlush = true;

            fileMode.createFileMode = EM_CreateFileMode.UNBOUND;
        }

        public StreamWriterWrapper(string path, CreateFileMode fileMode)
        {
            try
            {
                this.filePath = path;
                this.fileMode = new CreateFileMode(fileMode);
                string file = CreateNewFile();
                sw = new StreamWriter(file, false, Encoding.Default);
                sw.AutoFlush = true;
                sw.Flush();
            }
            catch (Exception e)
            {

            }
        }

        public void Write(byte[] data)
        {

        }

        public void WriteLine(StringBuilder stringBuilder)
        {
            if (fileMode.createFileMode == EM_CreateFileMode.CREATE_BY_SIZE)
            {
                long length = sw.BaseStream.Length;
                long lineLength = stringBuilder.Length;
                long nbytes = length + lineLength;
                //生成新文件
                if (nbytes > fileMode.fileSize * 1024)
                {
                    if (fileMode.isAutoDel)
                    {
                        DelOldFile();
                    }
                    string file = CreateNewFile();
                    //关闭旧的描述符
                    if (sw != null)
                    {
                        sw.Close();
                    }
                    sw = new StreamWriter(file, false, Encoding.Default);
                    sw.AutoFlush = true;
                    if (!string.IsNullOrEmpty(title))
                    {
                        sw.WriteLine(title);
                    }
                }

            }
            else if (fileMode.createFileMode == EM_CreateFileMode.CREATE_BY_TIME)
            {
                DateTime nowTm = DateTime.Now;
                TimeSpan ts = nowTm - firstWriteTm;
                TimeSpan tsOfSetting = new TimeSpan(0, fileMode.tmSpan, 0);
                if (ts >= tsOfSetting)
                {
                    if (fileMode.isAutoDel)
                    {
                        DelOldFile();
                    }
                    string file = CreateNewFile();
                    //关闭旧的描述符
                    if (sw != null)
                    {
                        sw.Close();
                    }
                    sw = new StreamWriter(file, false, Encoding.Default);
                    sw.AutoFlush = true;
                    if (!string.IsNullOrEmpty(title))
                    {
                        sw.WriteLine(title);
                    }
                }
            }

            sw.WriteLine(stringBuilder);
        }

        public void WriteLine(string value)
        {
            if (fileMode.createFileMode == EM_CreateFileMode.CREATE_BY_SIZE)
            {
                long length = sw.BaseStream.Length;
                long nbytes = length + Encoding.Default.GetByteCount(value);
                //生成新文件
                if (nbytes > fileMode.fileSize * 1024)
                {
                    if (fileMode.isAutoDel)
                    {
                        DelOldFile();
                    }
                    string file = CreateNewFile();
                    //关闭旧的描述符
                    if (sw != null)
                    {
                        sw.Close();
                    }
                    sw = new StreamWriter(file, false, Encoding.Default);
                    sw.AutoFlush = true;
                    if (!string.IsNullOrEmpty(title))
                    {
                        sw.WriteLine(title);
                    }
                }

            }
            else if (fileMode.createFileMode == EM_CreateFileMode.CREATE_BY_TIME)
            {
                DateTime nowTm = DateTime.Now;
                TimeSpan ts = nowTm - firstWriteTm;
                TimeSpan tsOfSetting = new TimeSpan(0, fileMode.tmSpan, 0);
                if (ts >= tsOfSetting)
                {
                    if (fileMode.isAutoDel)
                    {
                        DelOldFile();
                    }
                    string file = CreateNewFile();
                    //关闭旧的描述符
                    if (sw != null)
                    {
                        sw.Close();
                    }
                    sw = new StreamWriter(file, false, Encoding.Default);
                    sw.AutoFlush = true;
                    if (!string.IsNullOrEmpty(title))
                    {
                        sw.WriteLine(title);
                    }
                }
            }
            if (sw == null)
            {
                sw = new StreamWriter(filePath);
                Console.WriteLine("sw =  null");
            }
            sw?.WriteLine(value);
        }

        private void DelOldFile()
        {
            try
            {
                DriveInfo driveInfo = new DriveInfo(filePath.Substring(0, 1));
                long availableFreeSpace = driveInfo.AvailableFreeSpace;
                //Console.WriteLine(availableFreeSpace/1024/1024);
                if (availableFreeSpace < 1048576) // 如果小于1M
                {
                    //Console.WriteLine("开始删除");

                    string path = filePath.Replace("//", "\\").Replace("/", "\\");
                    int index = path.LastIndexOf('\\');

                    string fileName = filePath.Substring(0, index);
                    DirectoryInfo dirInfo = new DirectoryInfo(fileName);
                    FileInfo[] files = dirInfo.GetFiles();
                    if (files.Length < 4) return;

                    var sortedFiles = files.OrderBy(f => f.CreationTime).ToArray();

                    for (int i = 0; i < 2; i++)
                    {
                        sortedFiles[i].Delete();
                    }
                }

            }
            catch (Exception)
            {

            }
        }

        public void WriteTitle()
        {
            if (!string.IsNullOrEmpty(title))
            {
                WriteLine(title);
            }
        }
        public string CreateNewFile()
        {
            //firstWriteTm = DateTime.Now;

            //string newFile = "";
            //int index = filePath.LastIndexOf('.');
            //if (index > 0 && index < filePath.Length - 1) //不是头和尾
            //{
            //    string extendName = filePath.Substring(index, filePath.Length - index);
            //    string fileName = filePath.Substring(0, index);
            //    string tm = firstWriteTm.ToString("yyyyMMddHHmmssfff");
            //    newFile = fileName + tm + extendName;
            //}
            //else
            //{
            //    newFile = filePath + fileSeq.ToString("D3");
            //}

            //return newFile;
            return filePath;
        }


        private string title;

        public void SetTitle(string title)
        {
            this.title = title;
        }

        public void Close()
        {
            if (sw != null) sw.Close();
        }


    }


}